﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FTP_progress
{
    public  class Sqlite
    {
        private readonly string _connectionString;
        // 数据库文件位置：数据库文件名
        private static readonly string databasePath = @"RobotConfigureDB";

        public Sqlite()
        {
            _connectionString = $"Data Source={databasePath};Version=3;";
        }

        /// <summary>
        /// 打开数据库连接
        /// </summary>
        /// <returns>SQLiteConnection 对象</returns>
        private SQLiteConnection OpenConnection()
        {
            var connection = new SQLiteConnection(_connectionString);
            connection.Open();
            return connection;
        }

        /// <summary>
        /// 通用方法：执行非查询命令（增、删、改）
        /// </summary>
        /// <param name="query">SQL 查询语句</param>
        /// <param name="parameters">查询参数</param>
        /// <returns>受影响的行数</returns>
        public int ExecuteNonQuery(string query, Dictionary<string, object> parameters = null)
        {
             var connection = OpenConnection();
             var command = new SQLiteCommand(query, connection);
            // 添加参数
            if (parameters != null)
            {
                foreach (var param in parameters)
                {
                    command.Parameters.AddWithValue(param.Key, param.Value);
                }
            }
            return command.ExecuteNonQuery();
        }

        /// <summary>
        /// 通用方法：执行查询并返回结果
        /// </summary>
        /// <param name="query">SQL 查询语句</param>
        /// <param name="parameters">查询参数</param>
        /// <returns>查询结果 DataTable</returns>
        public DataTable ExecuteQuery(string query, Dictionary<string, object> parameters = null)
        {
            var connection = OpenConnection();
            var command = new SQLiteCommand(query, connection);
            // 添加参数
            if (parameters != null)
            {
                foreach (var param in parameters)
                {
                    command.Parameters.AddWithValue(param.Key, param.Value);
                }
            }
            using (var adapter = new SQLiteDataAdapter(command))
            {
                var dataTable = new DataTable();
                adapter.Fill(dataTable);
                return dataTable;
            }
        }

        /// <summary>
        /// 增加方法
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="data"></param>
        public void Insert(string tableName, Dictionary<string, object> data)
        {
            var columns = string.Join(", ", data.Keys);
            var placeholders = string.Join(", ", data.Keys.Select(key => "@" + key));
            var query = $"INSERT INTO {tableName} ({columns}) VALUES ({placeholders})";
            ExecuteNonQuery(query, data);
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="whereClause"></param>
        /// <param name="parameters"></param>
        public void Delete(string tableName, string whereClause, Dictionary<string, object> parameters)
        {
            var query = $"DELETE FROM {tableName} WHERE {whereClause}";
            ExecuteNonQuery(query, parameters);
        }


        public void DeleteAll(string tableName, Dictionary<string, object> parameters)
        {
            var query = $"DELETE FROM  {tableName}";
            ExecuteNonQuery(query, parameters);   
        }


        /// <summary>
        /// 查询方法
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="whereClause"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public DataTable Select(string tableName, string whereClause = null, Dictionary<string, object> parameters = null)
        {
            var query = $"SELECT * FROM {tableName}";
            if (!string.IsNullOrEmpty(whereClause))
            {
                query += $" WHERE {whereClause}";
            }

            return ExecuteQuery(query, parameters);
        }

        /// <summary>
        /// 更新方法
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="data"></param>
        /// <param name="whereClause"></param>
        /// <param name="parameters"></param>
        public void Update(string tableName, Dictionary<string, object> data, string whereClause, Dictionary<string, object> parameters)
        {           
            var setClause = string.Join(", ", data.Keys.Select(key => $"{key} = @{key}"));
            var query = $"UPDATE {tableName} SET {setClause} WHERE {whereClause}";

            // 合并参数
            if (parameters == null)
            {
                parameters = new Dictionary<string, object>();
            }
            foreach (var param in data)
            {
                parameters[$"@{param.Key}"] = param.Value;
            }

            ExecuteNonQuery(query, parameters);
        }
    }
}
